package com.zhiwei.msf.infra.oauth.config;

import com.zhiwei.msf.infra.oauth.service.AuthorityInfoService;
import com.zhiwei.msf.infra.oauth.entity.AuthorityInfo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ZHIWEI.YANG
 * @time 2019/12/9 - 21:36
 * @decription 自定义资源权限
 */
@Component
public class AuthoritySourceConfig implements FilterInvocationSecurityMetadataSource, InitializingBean {

    private final Map<RequestMatcher, Collection<ConfigAttribute>> authorityInfoMap = new ConcurrentHashMap<>();

    @Autowired
    public AuthorityInfoService authorityInfoService;

    public AuthoritySourceConfig() {

    }

    /**
     * object 需授权操作的对象： 例如网址
     *
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation) object;
        HttpServletRequest httpServletRequest = filterInvocation.getRequest();

        Set<ConfigAttribute> allAttributes = new HashSet<>();
        for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : authorityInfoMap.entrySet()) {
            if (entry.getKey().matches(httpServletRequest)) {
                allAttributes.addAll(entry.getValue());
            }
        }
        return allAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        Set<ConfigAttribute> configAttributes = new HashSet<>();
        authorityInfoMap.forEach((key, value) -> configAttributes.addAll(value));
        return configAttributes;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }

    /**
     * 刷新权限
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void refresh(){
        List<AuthorityInfo> authorityInfoList = authorityInfoService.queryAllAuthorities();
        if(CollectionUtils.isEmpty(authorityInfoList)){
            return;
        }
        for(AuthorityInfo authorityInfo : authorityInfoList){
            RequestMatcher requestMatcher = new AntPathRequestMatcher(authorityInfo.getUrl());
            authorityInfoMap.put(requestMatcher, SecurityConfig.createList(authorityInfo.getEname()));
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.refresh();
    }
}